package com.example.controller;

import com.example.common.PageResult;
import com.example.common.Result;
import com.example.dto.StockOperationDTO;
import com.example.dto.StockRecordQueryDTO;
import com.example.service.StockRecordService;
import com.example.util.UserContextUtil;
import com.example.vo.StockRecordVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 库存记录Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/stock")
@RequiredArgsConstructor
public class StockRecordController {

    private final StockRecordService stockRecordService;
    private final UserContextUtil userContextUtil;

    /**
     * 商品入库
     */
    @PostMapping("/in")
    public Result<Boolean> stockIn(@RequestBody StockOperationDTO operationDTO) {
        try {
            // 设置操作类型
            operationDTO.setRecordType("IN");
            
            // 获取当前用户信息
            Long operatorId = userContextUtil.getCurrentUserId();
            String operatorName = userContextUtil.getCurrentUserNickname();

            // 如果昵称为空，使用用户名；如果用户名也为空，使用默认值
            if (operatorName == null || operatorName.trim().isEmpty()) {
                operatorName = userContextUtil.getCurrentUsername();
                if (operatorName == null || operatorName.trim().isEmpty()) {
                    operatorName = "系统用户";
                }
            }
            
            boolean success = stockRecordService.stockIn(operationDTO, operatorId, operatorName);
            return Result.success(success);
        } catch (Exception e) {
            log.error("商品入库失败", e);
            return Result.error("入库失败：" + e.getMessage());
        }
    }



    /**
     * 分页查询库存记录（包括入库和出库记录）
     */
    @GetMapping("/records")
    public Result<PageResult<StockRecordVO>> getPageList(StockRecordQueryDTO queryDTO) {
        try {
            // 不再强制设置记录类型，允许查询所有类型的记录
            // 如果前端传递了recordType参数，则按照该参数过滤
            
            log.info("查询库存记录，参数：{}", queryDTO);
            PageResult<StockRecordVO> result = stockRecordService.getPageList(queryDTO);
            log.info("查询结果：总数={}, 当前页数据条数={}", result.getTotal(), result.getRecords().size());
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询库存记录失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据商品ID查询库存记录
     */
    @GetMapping("/records/product/{productId}")
    public Result<List<StockRecordVO>> getByProductId(@PathVariable Long productId) {
        try {
            List<StockRecordVO> records = stockRecordService.getByProductId(productId);
            return Result.success(records);
        } catch (Exception e) {
            log.error("查询商品库存记录失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 导出库存记录
     */
    @GetMapping("/export")
    public Result<List<StockRecordVO>> exportRecords(StockRecordQueryDTO queryDTO) {
        try {
            List<StockRecordVO> records = stockRecordService.exportRecords(queryDTO);
            return Result.success(records);
        } catch (Exception e) {
            log.error("导出库存记录失败", e);
            return Result.error("导出失败：" + e.getMessage());
        }
    }
} 